package wxact

import (
	"log"

	"io/ioutil"

	"myproject/wx_test/src/wxmod"

	"github.com/labstack/echo"
)

type Resp struct{}

func (*Resp) Response(ctx echo.Context) error {
	//todo 判断发送信息IP地址是否为微信服务器
	//log.Println(ctx.RealIP())
	//for k:=range wxglob.ServerList {
	//	if ctx.RealIP() == wxglob.ServerList[k]{
	//		break
	//	}
	//	log.Println("消息来源不合法")
	//	return ctx.String(403,"消息来源不合法")
	//}

	var req wxmod.Request
	req.Signature = ctx.FormValue("signature")
	req.TimeStamp = ctx.FormValue("timestamp")
	req.Nonce = ctx.FormValue("nonce")

	if req.Signature == "" && req.TimeStamp == "" && req.Nonce == "" {
		log.Println("无任何数据")
		return ctx.String(403, "消息错误")
	}

	//生成hashcode
	hashcode, err := wxmod.GenHashcode(req)
	if err != nil {
		log.Println("系统错误，genHashcode")
		return ctx.String(500, "系统错误")
	}

	//检查签名是否匹配
	if hashcode != req.Signature {
		//消息来源不是微信
		log.Println("签名验证失败")
		return ctx.String(200, "")
	}

	log.Println("签名成功")

	//获取wx信息
	body, err := ioutil.ReadAll(ctx.Request().Body)
	if err != nil {
		log.Println(err)
		return err
	}
	log.Println(wxmod.BytesToStr(body))
	log.Println("MSG Received")

	//解析XML文件
	msgRec, err := wxmod.ParseXML(body)
	if err != nil {
		log.Println(err)
		return err
	}

	//控制器
	msgSend := checkMsgType(msgRec)
	log.Println("MSG Sended :", msgSend)

	return ctx.String(200, msgSend)
}

func checkMsgType(msgRec *wxmod.XmlData) string {
	var wxActXML WXActXML
	var wxActMB WXActMB

	switch msgRec.MsgType {
	default:
		log.Println("switch -> default")
		return "success"
	case "text":
		log.Println("switch -> text")
		//return wxActXML.RespNewsMsg(msgRec)
		wxActMB.MuBanMsg(msgRec)
	case "event":
		switch msgRec.Event {
		default:
			log.Println("switch -> event,default")
			return "success"
		case "subscribe":
			log.Println("switch -> subscribe")
			return wxActXML.RespNewsMsg(msgRec)
			//return wxActXML.DefaultResp(msgRec)
		case "SCAN":
			log.Println("switch -> SCAN")
			return "success"
			//case "CLICK":

		}

	}

	log.Println("outside switch")
	return "success"
}
